package com.huang.article.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huang.article.entity.Article;
import com.huang.article.service.ArticleService;
import com.huang.base.BaseController;
import com.huang.constant.Common;
import com.huang.enums.UserCodeEnum;
import com.huang.exception.BizException;
import com.huang.resp.CommonResult;
import com.huang.util.OauthUtils;
import com.huang.vo.LoginUserInfo;
import com.huang.vo.Pager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;

/**
 * @author han
 * @since 2022-02-08 15:09:37
 */
@Slf4j
@RestController
@RequestMapping("/article")
public class ArticleController extends BaseController {

    @Resource
    private ArticleService articleService;

    /**
     * 文章列表
     * @param pager  分页对象
     */
    @GetMapping("/list")
    public CommonResult list(@RequestBody Pager<Article> pager) {
        LoginUserInfo user = OauthUtils.getCurrentUser();
        if (null == user) {
            throw new BizException(CommonResult.error(UserCodeEnum.NOT_LOGIN));
        }

        QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
        if (!user.getAuthorities().contains(Common.SystemConfig.SUPER_ADMIN)) {
            pager.getDetailMap().put("userId", user.getUserId());
        }
        pager = (Pager<Article>) parse(pager, queryWrapper);

        queryWrapper.lambda().orderByDesc(Article::getTopDate);
        queryWrapper.lambda().orderByDesc(Article::getCreateDate);
        pager = articleService.page(pager, queryWrapper);
        return CommonResult.success(pager);
    }

    /**
     * 文章新增
     */
    @GetMapping("/add")
    public CommonResult add(@Validated @RequestBody Article article) {
        LoginUserInfo user = OauthUtils.getCurrentUser();
        article.setUserId(user.getUserId());
        if (article.getTop()) {
            article.setTopDate(LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli());
        }
        articleService.save(article);
        return CommonResult.success();
    }

    /**
     * 文章新增
     */
    @GetMapping("/edit")
    public CommonResult edit(@Validated @RequestBody Article article) {
    	log.info("文章新增入参: {}" , article);
        LoginUserInfo user = OauthUtils.getCurrentUser();
        article.setUserId(user.getUserId());
        if (article.getTop()) {
            article.setTopDate(LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli());
        }
        articleService.updateById(article);
        return CommonResult.success();
    }

}
